<template>
  <div class="app-container">
    <div class="dispatch-container">
      <div class="section">
        <div class="section-header-wrapper">
          <div class="section-header">任务派工</div>
        </div>
        <el-form ref="taskForm" :model="form.task" :rules="rules.task" label-width="100px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="班组名称" prop="teamName">
                <el-input v-model="form.task.teamName" placeholder="请选择班组" readonly @click.native="openSelectDialog('teamName')">
                  <i slot="suffix" class="el-input__icon el-icon-search"></i>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="任务负责人" prop="leader">
                <el-input v-model="form.task.leader" placeholder="请选择负责人" readonly @click.native="openSelectDialog('leader')">
                  <i slot="suffix" class="el-input__icon el-icon-search"></i>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="其他成员" prop="members">
                <el-input v-model="form.task.members" placeholder="请选择其他成员" readonly @click.native="openSelectDialog('members')">
                   <i slot="suffix" class="el-input__icon el-icon-search"></i>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注" prop="remarks">
                <el-input type="textarea" :rows="3" v-model="form.task.remarks" placeholder="请输入内容"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <div class="section">
         <div class="section-header-wrapper">
          <div class="section-header">质检派工</div>
        </div>
        <el-form ref="qcForm" :model="form.qc" :rules="rules.qc" label-width="100px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="质检部门" prop="qcDept">
                <el-input v-model="form.qc.qcDept" placeholder="请选择质检部门" readonly @click.native="openSelectDialog('qcDept')">
                   <i slot="suffix" class="el-input__icon el-icon-search"></i>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="质检人员" prop="qcPerson">
                <el-input v-model="form.qc.qcPerson" placeholder="请选择质检人员" readonly @click.native="openSelectDialog('qcPerson')">
                   <i slot="suffix" class="el-input__icon el-icon-search"></i>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注" prop="remarks">
                <el-input type="textarea" :rows="3" v-model="form.qc.remarks" placeholder="请输入内容"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <div class="text-center" v-if="!showMaterialList" style="margin: 20px 0;">
        <el-button type="primary" plain @click="handleRequestMaterials" icon="el-icon-document-add">申请物料</el-button>
      </div>

      <div class="section" v-if="showMaterialList">
        <div class="section-header-wrapper">
          <div class="section-header">领料清单</div>
        </div>
        <el-table :data="form.materials" style="width: 100%">
          <el-table-column prop="materialCode" label="物料编码" />
          <el-table-column prop="materialName" label="物料名称" />
          <el-table-column prop="batchNo" label="批次号" >
             <template slot-scope="scope">
                <span v-if="scope.row.batchNo">{{ scope.row.batchNo }}</span>
                <span v-else style="color: #909399;">待选择</span>
            </template>
          </el-table-column>
          <el-table-column label="申请数量" width="150">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.quantity" size="mini" :min="0" :precision="3" />
            </template>
          </el-table-column>
          <el-table-column prop="unitName" label="单位" width="80" />
          <el-table-column label="操作" width="120" align="center">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                :icon="scope.row.batchNo ? 'el-icon-refresh' : 'el-icon-check'"
                @click="handleSelectBatch(scope.row, scope.$index)"
              >{{ scope.row.batchNo ? '更换批次' : '选择批次' }}</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="footer-buttons">
      <el-button @click="handleCancel">关 闭</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </div>
    <!-- 用户选择对话框 -->
    <select-user-dialog
      :visible.sync="selectDialog.visible"
      :title="selectDialog.title"
      :multi="selectDialog.multi"
      @confirm="handleSelectConfirm"
    />
    <!-- 批次选择对话框 -->
    <select-batch-dialog
      :visible.sync="batchDialog.visible"
      :title="batchDialog.title"
      :material-id="batchDialog.materialId"
      :material-code="batchDialog.materialCode"
      @confirm="handleBatchConfirm"
    />
  </div>
</template>

<script>
import SelectUserDialog from './SelectUserDialog';
import SelectBatchDialog from './SelectBatchDialog'; // 1. 引入组件
import { getMaterialRequirements, createDispatch } from '@/api/sc/dispatch';

export default {
  name: "DispatchPage",
  components: { SelectUserDialog, SelectBatchDialog }, // 2. 注册组件
  data() {
    return {
      showMaterialList: false,
      batchDialog: { // 3. 管理对话框状态
        visible: false,
        title: '',
        materialId: null,
        materialCode: null,
        currentRowIndex: -1
      },
      selectDialog: {
        visible: false,
        title: '',
        multi: false,
        type: '' // To distinguish which field is being selected
      },
      form: {
        task: {
          teamName: '',
          leader: '',
          members: '',
          remarks: '',
          teamId: null,
          leaderId: null,
          memberIds: null
        },
        qc: {
          qcDept: '',
          qcPerson: '',
          remarks: '',
          qcDeptId: null,
          qcPersonId: null
        },
        materials: []
      },
      rules: {
        task: {
          teamName: [{ required: true, message: "班组名称不能为空", trigger: "change" }],
          leader: [{ required: true, message: "任务负责人不能为空", trigger: "change" }]
        },
        qc: {
          qcDept: [{ required: true, message: "质检部门不能为空", trigger: "change" }],
          qcPerson: [{ required: true, message: "质检人员不能为空", trigger: "change" }]
        }
      }
    };
  },
  created() {
    this.workOrderTaskId = this.$route.query.id;
    if (!this.workOrderTaskId) {
      this.$modal.alertError("无效的工序任务ID").then(() => {
        this.$tab.closePage();
      });
    }
  },
  methods: {
    openSelectDialog(type) {
        this.selectDialog.type = type;
        this.selectDialog.visible = true;
        
        switch(type) {
            case 'teamName':
                this.selectDialog.title = '选择班组';
                this.selectDialog.multi = false; // Assuming a team is a single entity/user for now
                break;
            case 'leader':
                this.selectDialog.title = '选择任务负责人';
                this.selectDialog.multi = false;
                break;
            case 'members':
                this.selectDialog.title = '选择其他成员';
                this.selectDialog.multi = true;
                break;
            case 'qcDept':
                this.selectDialog.title = '选择质检部门';
                this.selectDialog.multi = false; // Assuming a dept is a single entity/user for now
                break;
            case 'qcPerson':
                this.selectDialog.title = '选择质检人员';
                this.selectDialog.multi = false;
                break;
        }
    },
    handleSelectConfirm(selection) {
        const type = this.selectDialog.type;
        if (this.selectDialog.multi) {
            this.form.task.members = selection.map(u => u.nickName).join(', ');
            this.form.task.memberIds = selection.map(u => u.userId);
        } else {
            const user = selection[0];
            switch(type) {
                 case 'teamName':
                    this.form.task.teamName = user.nickName; // Or deptName if you create a dept dialog
                    this.form.task.teamId = user.userId;
                    break;
                case 'leader':
                    this.form.task.leader = user.nickName;
                    this.form.task.leaderId = user.userId;
                    break;
                case 'qcDept':
                    this.form.qc.qcDept = user.nickName; // Or deptName
                    this.form.qc.qcDeptId = user.userId;
                    break;
                case 'qcPerson':
                    this.form.qc.qcPerson = user.nickName;
                    this.form.qc.qcPersonId = user.userId;
                    break;
            }
        }
    },
    
    handleSelectBatch(row, index) { // 4. 修改点击事件
      this.batchDialog.title = `为【${row.materialName}】选择库存批次`;
      this.batchDialog.materialId = row.materialId;
      this.batchDialog.materialCode = row.materialCode;
      this.batchDialog.currentRowIndex = index;
      this.batchDialog.visible = true;
    },

    handleBatchConfirm(selectedBatches) { // 5. 实现confirm处理器
      const index = this.batchDialog.currentRowIndex;
      if (index === -1) return;

      const targetRow = this.form.materials[index];
      
      // 这里简化处理：只取第一个选择的批次
      // 实际业务中可能需要处理多批次选择的汇总逻辑
      const firstBatch = selectedBatches[0];
      targetRow.inventoryId = firstBatch.inventoryId;
      targetRow.batchNo = firstBatch.batchNo;
      
      // 可选：自动填充申请数量为该批次的可用量
      // targetRow.quantity = firstBatch.availableQty;

      this.$message.success(`已为【${targetRow.materialName}】选择批次：${firstBatch.batchNo}`);
    },

    handleChangeBatch(index) {
      this.handleSelectBatch(this.form.materials[index], index);
    },
    handleRequestMaterials() {
      if (!this.workOrderTaskId) {
        this.$modal.msgError("缺少工序任务ID，无法获取物料清单");
        return;
      }
      this.$modal.loading("正在根据工艺路径自动推荐物料...");
      getMaterialRequirements(this.workOrderTaskId).then(response => {
        if (response.code === 200 && response.data) {
           this.form.materials = response.data.map(item => ({
            ...item,
            inventoryId: null, // 待选择
            batchNo: '', // 待选择
            quantity: item.quantity, // 默认申请数量为计算的需求数量
          }));
          this.showMaterialList = true;
          this.$message.success("物料清单已自动生成，请为每项物料选择库存批次。");
        } else {
           this.$modal.msgError("获取物料清单失败");
        }
      }).catch(err => {
        console.error("API Error:", err);
        this.$modal.msgError("获取物料清单时发生错误");
      }).finally(() => {
         this.$modal.closeLoading();
      });
    },
    handleCancel() {
      this.$router.go(-1);
    },
    handleSubmit() {
      let taskFormValid = false;
      let qcFormValid = false;

      this.$refs.taskForm.validate(valid => { taskFormValid = valid; });
      this.$refs.qcForm.validate(valid => { qcFormValid = valid; });

      if (!taskFormValid || !qcFormValid) {
        this.$modal.msgError("请填写任务派工和质检派工的必填项");
        return;
      }

      // 校验物料清单是否都已选择批次
      if (this.showMaterialList) {
        const unselectedMaterials = this.form.materials.filter(m => !m.inventoryId);
        if (unselectedMaterials.length > 0) {
          const materialNames = unselectedMaterials.map(m => m.materialName).join('、');
          this.$modal.msgError(`物料【${materialNames}】尚未选择库存批次`);
          return;
        }
      }

      // 组装提交后端的DTO
      const dispatchDto = {
        workOrderTaskId: this.workOrderTaskId,
        teamId: this.form.task.teamId,
        leaderId: this.form.task.leaderId,
        memberIds: this.form.task.memberIds,
        remark: this.form.task.remarks, // 可以考虑合并两个备注
        qcDeptId: this.form.qc.qcDeptId,
        qcPersonId: this.form.qc.qcPersonId,
        materialRequests: this.form.materials.map(m => ({
          inventoryId: m.inventoryId,
          materialId: m.materialId,
          batchNo: m.batchNo,
          quantity: m.quantity
        }))
      };

      this.$modal.loading("正在提交派工...");
      createDispatch(dispatchDto).then(response => {
        this.$modal.closeLoading();
        if (response.code === 200) {
          this.$modal.msgSuccess("派工成功");
          this.handleCancel();
        } else {
          this.$modal.msgError(response.msg || "派工失败");
        }
      }).catch(err => {
        this.$modal.closeLoading();
        console.error("Dispatch API Error:", err);
        this.$modal.msgError("派工时发生错误");
      });
    }
  }
};
</script>

<style scoped>
.mb8 {
  margin-bottom: 8px;
}
.dispatch-container {
  padding: 20px;
  max-width: 900px;
  margin: 0 auto;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}
.section {
  margin-bottom: 25px;
  border: 1px solid #e8e8e8;
  padding: 30px 20px 20px 20px;
  border-radius: 5px;
}
.section-header-wrapper {
  text-align: center;
  margin: -45px auto 25px;
}
.section-header {
    display: inline-block;
    padding: 0 15px;
    background: #fff;
    font-size: 18px;
    font-weight: 600;
    color: #333;
}
.footer-buttons {
  text-align: center;
  margin-top: 20px;
}
.text-center {
  text-align: center;
}
</style> 